from system.host.models import Host, Group
from utils.serializers import CustomModelSerializer
from rest_framework import serializers


class HostSerializer(CustomModelSerializer):
    """
    主机管理 简单序列化器
    """

    class Meta:
        model = Host
        fields = '__all__'


class HostChildrenSerializer(CustomModelSerializer):
    """
    主机管理 简单序列化器
    """
    key = serializers.CharField(source='id')
    value = serializers.CharField(source='id')
    title = serializers.CharField(source='hostname')
    isLeaf = serializers.BooleanField(default=True)

    class Meta:
        model = Host
        fields = ('id', 'key', 'value', 'title', 'isLeaf', 'ip', 'hostname')


class HostCreateUpdateSerializer(CustomModelSerializer):
    """
    主机管理 创建/更新时的列化器
    """

    class Meta:
        model = Host
        fields = '__all__'
        read_only_fields = ['id']


class GroupSerializer(CustomModelSerializer):
    """
    主机组管理 简单序列化器
    """
    key = serializers.CharField(source='id')
    value = serializers.CharField(source='id')
    title = serializers.CharField(source='name')
    children = serializers.SerializerMethodField()
    pid = serializers.SerializerMethodField()

    class Meta:
        model = Group
        fields = ('id', 'key', 'value', 'title', 'children', 'pid')

    def get_children(self, obj):
        if obj.self_parent:
            return GroupSerializer(obj.self_parent.order_by('sort_id'), many=True).data
        return None

    def get_pid(self, obj):
        return obj.parent.id if obj.parent else 0


class GroupWithHostsSerializer(CustomModelSerializer):
    """
    主机组-主机树序列化器
    """
    key = serializers.CharField(source='id')
    value = serializers.CharField(source='id')
    title = serializers.CharField(source='name')
    children = serializers.SerializerMethodField()

    class Meta:
        model = Group
        fields = ('id', 'key', 'value', 'title', 'children')

    def get_children(self, obj):
        list1 = list()
        if obj.group:
            for item in HostChildrenSerializer(obj.group.all(), many=True).data:
                list1.append(item)
        if obj.self_parent:
            for item in GroupWithHostsSerializer(obj.self_parent.order_by('sort_id'), many=True).data:
                list1.append(item)
        return list1


class GroupCreateUpdateSerializer(CustomModelSerializer):
    """
    主机组管理 创建/更新时的列化器
    """

    def create(self, validated_data):
        group = Group.objects.all().order_by('-sort_id').first()
        if group:
            validated_data['sort_id'] = group.sort_id + 1
        return super().create(validated_data)

    class Meta:
        model = Group
        fields = '__all__'
